package com.ias.agdis_r.netservice;

import android.os.Handler;
import android.text.TextUtils;

import com.ias.agdis_r.bean.other.GpsInfoBean;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.MessageManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.util.S;

import java.util.ArrayList;

/**
 * GPS发送线程
 * @author wanghu
 */
public class SendGpsThread extends Thread {

	private Handler handler;
	private double maxUp = 0.1;	// 超过10%不上报该信息
	private long interval = 5 * 1000;

	public SendGpsThread(Handler handler) {
		this.handler = handler;
		long value = 0;
		try {
			value = 1000 * DataBaseManager.getInstance().getLong(ParameterModel.T_GPS_INFO, ParameterModel.SEND_INTERVAL);
		} catch (Exception e) {
		}
		if (value != 0) {
			interval = value;
		}
	}

	@Override
	public void run() {
		if (ServiceManage.getInstance().getIsLogon()) {
			if (checkGPSStatus()) {
				if (ServiceManage.getInstance().getUsingPushService() != null) {
					ArrayList<GpsInfoBean> gpsList = JavaBeanManager.getInstance().getGpsArrayList();
					StringBuffer lastSendGpsMessage = new StringBuffer();
					for (GpsInfoBean bean : gpsList) {
						String strMinSpeed = DataBaseManager.getInstance().getString(ParameterModel.T_GPS_INFO, ParameterModel.MINSPEEDING);
						float minSpeed = S.isNotEmpty(strMinSpeed) ? Float.parseFloat(strMinSpeed) : 0;
						String strMaxSpeed = DataBaseManager.getInstance().getString(ParameterModel.T_GPS_INFO, ParameterModel.MAXSPEEDING);
						float maxSpeed = S.isNotEmpty(strMaxSpeed) ? Float.parseFloat(strMaxSpeed) : 100;

						float currSpeed = bean.getGpsSpeed();
						if (currSpeed < minSpeed) {
							currSpeed = 0;
						} else if (currSpeed >= maxSpeed * (1 + maxUp)) {
							currSpeed = maxSpeed;
						} else if (currSpeed > maxSpeed) {
							//超速报警
							System.out.println("SendGpsThread===currSpeed:" + currSpeed + "===GPS Speed is out of the limited ");
						}

						lastSendGpsMessage.append(MessageManager.getInstance().getGpsMessage(bean.getLongitude(), bean.getLatitude(), String.valueOf(currSpeed), bean.getBear(), bean.getGpsTime()));
					}//end for

					//发送GPS信息
					if (!TextUtils.isEmpty(lastSendGpsMessage)) {
						ServiceManage.getInstance().sendMessage(lastSendGpsMessage.toString());
						JavaBeanManager.getInstance().clearArrayList();
					}
				}
			}
		} else {
			Thread.interrupted();
		}
		handler.postDelayed(this, interval);
	}
	
	/**
	 * 检测GPS状态
	 * @return
	 */
	private boolean checkGPSStatus() {
		// 如果没有GPS服务
		if (ServiceManage.getInstance().getGpsService() == null) {
			return false;
		}
		// 检测是否有收集到的GPS点
		ArrayList<GpsInfoBean> gpsArrayList = JavaBeanManager.getInstance().getGpsArrayList();
		if (gpsArrayList == null || gpsArrayList.isEmpty()) {
			return false;
		}
		return true;
	}
}
